<template>
  <AppLayout :nav-title="pageTitle" :show-left-arrow="true" :show-tabbar="false">
    <PageLayout :loading="pageLoading" :error="pageError" @retry="init">
      <div class="staff-edit">
        <BaseForm
          v-model="form"
          :submit-loading="submitLoading"
          submit-button-text="保存"
          reset-button-text="重置"
          @submit="handleSubmit"
          @failed="handleFailed"
          @reset="handleReset"
        >
          <van-field
            v-model="form.name"
            label="姓名"
            placeholder="请输入姓名"
            :rules="[
              { required: true, message: '请输入姓名' },
              { pattern: /^.{2,20}$/, message: '姓名长度2-20字符' }
            ]"
          />

          <van-field label="性别" :rules="[{ required: true, message: '请选择性别' }]">
            <template #input>
              <van-radio-group v-model="form.gender" direction="horizontal">
                <van-radio name="1">男</van-radio>
                <van-radio name="2" style="margin-left: 16px">女</van-radio>
              </van-radio-group>
            </template>
          </van-field>

          <van-field
            v-model="form.phone"
            label="手机号"
            type="tel"
            placeholder="请输入手机号"
            :rules="[
              { required: true, message: '请输入手机号' },
              { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确' }
            ]"
          />

          <van-field
            v-model="form.age"
            label="年龄"
            type="digit"
            placeholder="请输入年龄"
            :rules="[
              { required: true, message: '请输入年龄' },
              { validator: validateAge, message: '年龄需为16-65之间的整数' }
            ]"
          />

          <div class="upload-block">
            <BaseUpload
              v-model="documents"
              label="证件上传"
              :required="true"
              accept=".pdf,.jpg,.jpeg,.png,.doc,.docx"
              :multiple="true"
              :max-count="5"
              :max-size="20 * 1024 * 1024"
              :preview-image="true"
              :preview-full-image="true"
              :show-file-list="true"
              :upload-fn="uploadDocument"
              :tip="'支持PDF/图片/Word文档，单个文件最大20MB'"
            />
          </div>
        </BaseForm>
      </div>
    </PageLayout>
  </AppLayout>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { showToast } from 'vant'
import { useRoute, useRouter } from 'vue-router'
import { getEmployeeDetail, createEmployee, updateEmployee } from '@/api/store'
import { uploadDocument } from '@/api/upload'

const route = useRoute()
const router = useRouter()

const id = computed(() => route.params.id)
const isEdit = computed(() => !!id.value)
const pageTitle = computed(() => (isEdit.value ? '编辑员工' : '新增员工'))

const pageLoading = ref(false)
const pageError = ref(false)
const submitLoading = ref(false)

const form = ref({
  name: '',
  gender: '', // 1 男；2 女
  phone: '',
  age: ''
})

const documents = ref([])

const validateAge = (val) => {
  const num = Number(val)
  return Number.isInteger(num) && num >= 16 && num <= 65
}

const init = async () => {
  try {
    pageLoading.value = true
    pageError.value = false
    if (isEdit.value) {
      const { data } = await getEmployeeDetail(id.value)
      form.value = {
        name: data.name || '',
        gender: String(data.gender || ''),
        phone: data.phone || '',
        age: String(data.age || '')
      }
      // documents 保持为空，上传后以当前页面为准
    }
  } catch (e) {
    console.error('初始化编辑页面失败:', e)
    pageError.value = true
  } finally {
    pageLoading.value = false
  }
}

const handleSubmit = async () => {
  try {
    submitLoading.value = true
    // 证件必填校验
    if (!documents.value || documents.value.length === 0) {
      showToast('请上传至少一个证件')
      return
    }
    const payload = {
      ...form.value,
      gender: Number(form.value.gender),
      age: Number(form.value.age),
      // 将上传的文件简单映射为URL或文件名（mock环境）
      certificates: documents.value.map(f => ({ name: f.name || f.url, url: f.url }))
    }

    if (isEdit.value) {
      await updateEmployee(id.value, payload)
    } else {
      // 兼容现有mock接口的必填字段
      await createEmployee({
        ...payload,
        idCard: '110101199001010000',
        departmentId: 1
      })
    }

    showToast('保存成功')
    router.replace({ name: 'StoreStaff' })
  } catch (e) {
    console.error('保存失败:', e)
    showToast((e && e.message) || '保存失败，请稍后重试')
  } finally {
    submitLoading.value = false
  }
}

const handleFailed = (err) => {
  console.warn('表单校验失败:', err)
  showToast('请完善表单信息')
}

const handleReset = () => {
  form.value = { name: '', gender: '', phone: '', age: '' }
  documents.value = []
}

onMounted(async () => {
  await init()
})
</script>

<style scoped lang="scss">
.staff-edit {
  background: #fff;
}

.upload-block {
  padding: 8px 12px 16px;
}
</style>